package cn.com.shaom.learning.sb.security.example2;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName: User
 * Description:
 * Date: 2017/12/27 10:37 【需求编号】
 *
 * @author Shaom
 * @version V1.0.0
 */
@Entity
public class User implements UserDetails {

    @Id
    @GeneratedValue
    private Long id;
    private String name;
    private String pwd;

    @ManyToMany(cascade = {CascadeType.PERSIST}, fetch = FetchType.EAGER)
    private List<Role> roles;


    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("User{");
        sb.append("id='").append(id).append('\'');
        sb.append(", name='").append(name).append('\'');
        sb.append(", pwd='").append(pwd).append('\'');
        sb.append('}');
        return sb.toString();
    }

    /**
     * 授权处理
     * 获取的角色数据
     * 在 SecurityExpressionRoot 中的hasAnyAuthorityName()方法中会获取并判断
     *
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> auths = new ArrayList<>();
        List<Role> roles = getRoles();
        auths.addAll(roles.stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList()));

        // 如果涉及到资源，可以使用 SwitchUserGrantedAuthority，或者直接存放在 SimpleGrantedAuthority 也行
        return auths;
    }

    @Override
    public String getPassword() {
        return pwd;
    }

    @Override
    public String getUsername() {
        return name;
    }

    @Override
    public boolean isAccountNonExpired() {
        //是否过期
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        //账户未锁定为true
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        //证书不过期为true
        return true;
    }

    @Override
    public boolean isEnabled() {
        //是否可用
        return true;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }
}
